<template>
  <view class="container">
    <view class="input-container">
      <text class="label">输入增加的积分数量：</text>
      <input type="number" class="input" v-model="pointsToAdd" placeholder="请输入积分数量" />
    </view>
    <button class="add-button" @click="addPoints">增加积分</button>
  </view>
</template>

<script>
import { getTokenFromFile } from '@/utils/utils.js'; // 确保路径正确

export default {
  data() {
    return {
      pointsToAdd: 0, // 用户输入的积分数量
      token: '', // 初始化token
      pauseTime: 0, // 每次请求后暂停1秒
    };
  },
  methods: {
    // 增加积分的方法
    async addPoints() {
      try {
        this.token = await getTokenFromFile();
        if (this.pointsToAdd > 0) {
          for (let i = 0; i < this.pointsToAdd; i++) {
            await this.sendRequest(1); // 每次只增加1个积分
            await new Promise(resolve => setTimeout(resolve, this.pauseTime * 1000)); // 暂停1秒
          }
          this.pointsToAdd = 0; // 重置输入框
          uni.showToast({
            title: '所有积分增加请求已完成',
            icon: 'success',
            duration: 2000
          });
        } else {
          uni.showToast({
            title: '请输入有效的积分数量',
            icon: 'none',
            duration: 2000
          });
        }
      } catch (error) {
        console.error('获取token失败:', error);
        uni.showToast({
          title: '获取token失败',
          icon: 'none',
          duration: 2000
        });
      }
    },
    // 发送单个请求的方法
    sendRequest(points) {
      const url = 'http://106.15.182.86:9099/studycorrect';
      const headers = {
        'Authorization': this.token,
        'Content-Type': 'application/json'
      };
      const data = {
        points: points
      };

      return new Promise((resolve, reject) => {
        uni.request({
          url: url,
          method: 'POST',
          header: headers,
          data: data,
          success: (res) => {
            if (res.statusCode === 200) {
              console.log(`成功增加 ${points} 积分`);
              resolve(res);
            } else {
              reject(new Error('积分增加失败'));
            }
          },
          fail: (err) => {
            reject(new Error('请求失败'));
          }
        });
      });
    },
    // 获取token的方法
    async fetchToken() {
      try {
        this.token = await getTokenFromFile();
        console.log('Token fetched successfully:', this.token);
      } catch (error) {
        console.error('Failed to fetch token:', error);
        uni.showToast({
          title: '获取token失败',
          icon: 'none',
          duration: 2000
        });
      }
    }
  },
  mounted() {
    this.fetchToken(); // 在组件挂载后获取token
  }
};
</script>

<style scoped>
.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.input-container {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.label {
  margin-right: 10px;
}

.input {
  border: 1px solid #ccc;
  border-radius: 4px;
  padding: 8px;
  font-size: 16px;
}

.add-button {
  background-color: #007aff;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 10px 20px;
  font-size: 16px;
  cursor: pointer;
}
</style>